package com.shungen.realapigateway.service.impl;

import com.shungen.realapigateway.service.DynamicRouteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author shungen
 * @date 2024年08月13日 14:27
 */
@Service
public class DynamicRouteServiceImpl implements DynamicRouteService {

    @Autowired
    private RouteDefinitionRepository routeDefinitionRepository;

    @Autowired
    private ApplicationEventPublisher publisher;

    public void refreshRoutes(List<RouteDefinition> routeDefinitions) {
        // 清除所有旧路由
        routeDefinitionRepository.getRouteDefinitions()
                .subscribe(routeDefinition -> routeDefinitionRepository.delete(Mono.just(routeDefinition.getId())).subscribe());

        // 增加新路由
        routeDefinitions.forEach(routeDefinition -> routeDefinitionRepository.save(Mono.just(routeDefinition)).subscribe());

        // 发布路由刷新事件
        this.publisher.publishEvent(new RefreshRoutesEvent(this));
    }

}
